package com.magicalcoder.youyamvc.web.controller.web.goodsimg;
import com.magicalcoder.youyamvc.app.goodsimg.service.GoodsImgService;
import com.magicalcoder.youyamvc.app.goodsimg.service.GoodsImgProxyService;
import com.magicalcoder.youyamvc.app.goodsimg.constant.GoodsImgConstant;
import com.magicalcoder.youyamvc.app.goodsimg.util.GoodsImgUtil;
import com.magicalcoder.youyamvc.web.controller.web.goodsimg.param.GoodsImgRequest;
import com.magicalcoder.youyamvc.web.controller.web.goodsimg.param.GoodsImgResponse;
import com.magicalcoder.youyamvc.app.model.GoodsImg;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.MapUtil;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.common.dto.AjaxData;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.spring.web.WebLoginController;
import com.magicalcoder.youyamvc.web.common.BaseController;
import com.magicalcoder.youyamvc.app.userweb.util.UserWebUtil;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.*;
import java.math.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:323237052
*/

@RequestMapping({"/user/goods_img"})
@Controller
public class GoodsImgUserController extends WebLoginController
{

    @Resource
    private GoodsImgService goodsImgService;
    @Resource
    private GoodsImgProxyService goodsImgProxyService;
    /** method:GET
    *   url:/user/goods_img/list/{pageIndex}/{pageSize}?...
    *   demo:/user/goods_img/list/1/20
    *   获取商品相册分页数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  是   @pageIndex                     (Integer)当前页码 [1,n]
    *  是   @pageSize                      (Integer)每页条数 [1,n]
    *  否   @callback                      (String)回调方法
    *  否   @orderBySqlField               (String)排序字段
    *  否   @descAsc                       (String)desc|asc
    *  否   @encode                        (String)编码 默认UTF-8
    *  否   @id                     (Long)主键 
    *  否   @imgName                     (String)图片名称 
    *  否   @imgUrl                     (String)地址 
    *  否   @goodsId                     (Long)商品 
    *  否   @type                     (Integer)类型 [{"":"全部"},{"0":"类型一"},{"1":"类型二"}]
    *  否   @status                     (Boolean)状态 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *  否   @imgDesc                     (String)描述 
    *  否   @createTime                     (Date)创建时间 
    *  否  like @imgNameFirst                     (String)图片名称 
    *  否   @goodsIdFirst                     (Long)商品 
    *  否   @typeFirst                     (Integer)类型 [{"":"全部"},{"0":"类型一"},{"1":"类型二"}]
    *  否   @statusFirst                     (Boolean)状态 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                [{
    *              id         (Long)主键 
    *              imgName         (String)图片名称 
    *              imgUrl         (String)地址 
    *              goodsId         (Long)商品 
    *              type         (Integer)类型 [{"":"全部"},{"0":"类型一"},{"1":"类型二"}]
    *              status         (Boolean)状态 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *              imgDesc         (String)描述 
    *              createTime         (Date)创建时间 
    *      }]
    *   }
    */
    @RequestMapping(value={"list/{pageIndex}/{pageSize}"}, method={RequestMethod.GET})
    public void list(@PathVariable Integer pageIndex,@PathVariable Integer pageSize,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")   Long id,
        @RequestParam(required = false,value ="imgName")   String imgName,
        @RequestParam(required = false,value ="imgUrl")   String imgUrl,
        @RequestParam(required = false,value ="goodsId")   Long goodsId,
        @RequestParam(required = false,value ="type")   Integer type,
        @RequestParam(required = false,value ="status")   Boolean status,
        @RequestParam(required = false,value ="imgDesc")   String imgDesc,
        @RequestParam(required = false,value ="createTime")      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTime,
        @RequestParam(required = false,value ="imgNameFirst")                            String imgNameFirst ,
        @RequestParam(required = false,value ="goodsIdFirst")                            Long goodsIdFirst ,
        @RequestParam(required = false,value ="typeFirst")                            Integer typeFirst ,
        @RequestParam(required = false,value ="statusFirst")                            Boolean statusFirst ,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            String orderBySqlFieldStr = ",id,img_name,img_url,goods_id,type,status,img_desc,create_time,";
            String orderBy = ProjectUtil.filterOrderBy(orderBySqlFieldStr,orderBySqlField,descAsc);
            if(StringUtils.isBlank(orderBy)){
                orderBy = "";
            }
            pageSize = Math.min(GoodsImgConstant.PAGE_MAX_SIZE,pageSize);
            int idx = (pageIndex.intValue() - 1) * pageSize;
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap("orderBy", orderBy,
         "id",id,
         "imgName",imgName,
         "imgUrl",imgUrl,
         "goodsId",goodsId,
         "type",type,
         "status",status,
         "imgDesc",imgDesc,
         "createTime",createTime,
                    "imgNameFirst",imgNameFirst ,
                    "goodsIdFirst",goodsIdFirst ,
                    "typeFirst",typeFirst ,
                    "statusFirst",statusFirst ,
                "start",idx,"limit", pageSize ,"userId",_userId);

            List<GoodsImg> pageList = this.goodsImgService.getGoodsImgList(query);
            toWebSuccessJson(callback,encode,response, coverToResponseList(pageList));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    private List<GoodsImgResponse> coverToResponseList(List<GoodsImg> pageList){
        if(ListUtils.isBlank(pageList)){
            return null;
        }
        return Copyer.copy(pageList,GoodsImgResponse.class);
    }


    /** method:GET
    *   url:/user/goods_img/item?...
    *   demo:/user/goods_img/item
    *   获取商品相册详情数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
     *  否  @id        (Long) 主键
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                {
    *              id         (Long)主键 
    *              imgName         (String)图片名称 
    *              imgUrl         (String)地址 
    *              goodsId         (Long)商品 
    *              type         (Integer)类型 [{"":"全部"},{"0":"类型一"},{"1":"类型二"}]
    *              status         (Boolean)状态 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *              imgDesc         (String)描述 
    *              createTime         (Date)创建时间 
    *      }
    *   }
    */
    @RequestMapping(value={"item"}, method={RequestMethod.GET})
    public void item(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Long id,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
                     "id",id,
                "userId",_userId
            );
            GoodsImg goodsImg = this.goodsImgService.selectFirstGoodsImg(query);
            toWebSuccessJson(callback,encode,response, Copyer.copy(goodsImg,new GoodsImgResponse()));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    /** method:post
    *   url:/user/goods_img/save?...
    *   demo:/user/goods_img/save?...
    *   保存商品相册
    *   是否需要登录               是
    *是否必须         入参         注释
    * 否id (Long)主键  为空表示插入否则表示更新
    * 否imgName (String)图片名称  
    * 否imgUrl (String)地址  
    * 否goodsId (Long)商品  
    * 否type (Integer)类型 [{"":"全部"},{"0":"类型一"},{"1":"类型二"}] 
    * 否status (Boolean)状态 [{"":"全部"},{"false":"否"},{"true":"是"}] 
    * 否imgDesc (String)描述  
    * 否createTime (Date)创建时间  
    *
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:id 主键 Long
    *   }
    */
    @RequestMapping(value={"save"}  ,method={RequestMethod.POST})
    public void save(@ModelAttribute GoodsImgRequest goodsImgRequest,

        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        HttpServletRequest request,HttpServletResponse response) {
        Long _userId = UserWebUtil.userId(request);
        try{
            Long id = saveEntity(_userId,goodsImgRequest);
            toWebSuccessJson(callback,encode,response, id);
        }catch (BusinessException e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response,e.getErrorCode(), exceptionMsg);
            e.printStackTrace();
        }
        catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response, exceptionMsg);
            e.printStackTrace();
        }
    }

    private Long saveEntity(Long userId,GoodsImgRequest goodsImgRequest){
        if (goodsImgRequest.getId() == null) {
            GoodsImg goodsImg = new GoodsImg();
            Copyer.copy(goodsImgRequest,goodsImg);
            goodsImg.setCreateTime(new Date());
            return this.goodsImgService.insertGoodsImg(goodsImg);
        } else {
            GoodsImg entity = getEntity(userId,goodsImgRequest.getId());
            if(entity!=null){
                Copyer.reflectCopyZeroNotNull(goodsImgRequest, entity);
                this.goodsImgService.updateGoodsImg(entity);
            }
        }
        return goodsImgRequest.getId();
    }

    private GoodsImg getEntity(Long userId,Long id){
        return this.goodsImgService.selectOneGoodsImgWillThrowException(ProjectUtil.buildMap(
            "id",id));
    }

    /** method:get
    *   url:/user/goods_img/delete?...
    *   demo:/user/goods_img/delete?...

    *   删除商品相册
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
    *  否  @id        (Long) 主键
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:true||false
    *   }
    */
    @RequestMapping(value={"delete"}, method={RequestMethod.GET})
    public void delete(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Long id,
    HttpServletRequest request,HttpServletResponse response)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
            "id",id,
            "userId",_userId
            );
            this.goodsImgService.deleteGoodsImgList(query);
            toWebSuccessJson(callback,encode,response, true);
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }



}